package com.ly.demo.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.ly.demo.entity.SmResult;
import com.ly.demo.entity.ValidEntity;
import com.ly.demo.utils.ImageMergeUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

/**
 * @Author liuyang
 * @Date 2023/7/3 19:50
 **/
@RestController
@RequestMapping("/valid")
public class ValidController {
    @GetMapping("/test1")
    public SmResult test1(@RequestParam Long id) {
        return SmResult.ok();
    }

    @PostMapping("/test2")
    public SmResult test2(@Validated @RequestBody ValidEntity validEntity) {
        System.out.println(JSONUtil.toJsonStr(validEntity));
        return SmResult.ok();
    }

    @PostMapping("/test3")
    public SmResult test3(@RequestPart MultipartFile file,@RequestParam Long id) {
        return SmResult.ok(file.getName()+id);
    }

    public static void main(String[] args) throws IOException {
        String base64Image1="";
        String base64Image2="";
        String base64 = ImageMergeUtil.mergeImagesToBase64(CollUtil.newArrayList(base64Image1, base64Image2));

        // 保存合并后的图片到本地
        File outputfile = new File("merged_image.png");  // 保存的文件路径
        ImageIO.write( decodeBase64ToImage(base64), "png", outputfile);   // 写入文件
        System.out.println("图片已保存到本地: " + outputfile.getAbsolutePath());
    }

    // 将 Base64 字符串解码为 BufferedImage
    private static BufferedImage decodeBase64ToImage(String base64Str) throws IOException {
        // 去除 Base64 前缀，如果存在的话
        if (base64Str.contains(",")) {
            base64Str = base64Str.split(",")[1];
        }
        byte[] imageBytes = Base64.getDecoder().decode(base64Str);
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(bais);
    }

    // 将 BufferedImage 编码为 Base64 字符串
    private static String encodeImageToBase64(BufferedImage image, String format) throws IOException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

}
